package com.ffsky.cordova;

import android.content.Context;

import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaPreferences;
import org.apache.cordova.PluginEntry;
import org.apache.cordova.PluginManager;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CordovaKit {
    public static final String KEY_URL = "___URL";

    private static CordovaKit INSTANCE = null;

    public static CordovaKit getInstance() {
        if (INSTANCE == null) {
            synchronized (CordovaKit.class) {
                INSTANCE = new CordovaKit();
            }
        }
        return INSTANCE;
    }

    public static void unInstance() {
        if (INSTANCE != null) {
            INSTANCE.destroy();
            INSTANCE = null;
        }
    }

    private ExecutorService threadPool;
    private CordovaPreferences preferences;
    private ArrayList<PluginEntry> pluginEntries;
    private String launchUrl;

    protected CordovaKit() {
        threadPool = Executors.newCachedThreadPool();
    }

    public void destroy() {
        if (threadPool != null) {
            if (!threadPool.isShutdown()) {
                threadPool.shutdown();
                threadPool = null;
            }
        }
    }

    private boolean init = false;

    public void load(Context context) {
        if (!init) {
            ConfigXmlParser parser = new ConfigXmlParser();
            parser.parse(context);
            preferences = parser.getPreferences();
            pluginEntries = parser.getPluginEntries();
            launchUrl = parser.getLaunchUrl();
            init = true;
        }

    }

    public ExecutorService getThreadPool() {
        return threadPool;
    }

    public String getLaunchUrl() {
        return launchUrl;
    }

    public ArrayList<PluginEntry> getPluginEntries() {
        return pluginEntries;
    }

    public CordovaPreferences getPreferences() {
        return preferences;
    }
}
